package com.cw2.structural.proxy.jdk1;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkTiktokProxy1<T> implements InvocationHandler {

    private T tagert;

    public JdkTiktokProxy1(T tagert) {
        this.tagert = tagert;
    }

    /**
     * 创建代理类
     * 创建代理方法
     * @param tagert
     * @return
     * @param <T>
     */
    public static<T> T createProxy(T tagert) {
        Object o = Proxy.newProxyInstance(tagert.getClass().getClassLoader(),
                tagert.getClass().getInterfaces(),
                new JdkTiktokProxy1<>(tagert)
        );
        return (T)o;
    }

    /**
     * 返回增强类
     * @param target
     * @return
     * @param <T>
     */
    public static<T> T createProxy1(T target){
        Object proxyObject = Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new JdkTiktokProxy1<>(target)
        );
        return (T) proxyObject;
    }

    /**
     * 创建代理执行的方法
     * 执行的是 target 目标类
     * @return object
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理方法执行前");
        Object invoke = method.invoke(tagert, args);
        System.out.println("代理方法执行后");
        return invoke;
    }
}
